package dao.impl;

import dao.CommentDao;
import db.DBUtil;
import entity.Comment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class CommentDaoImpl implements CommentDao {
    @Override
    public int insertComment(Comment comment) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;

        String username = comment.getUsername();
        int userid = comment.getUserid();
        int articleid = comment.getArticleid();
        String commentContent = comment.getComment_content();
        String createTime = comment.getComment_date();

        String sql = "insert into comment(userid,articleid,comment_content,username,comment_date)values(?,?,?,?,?)";

        conn = DBUtil.getConnection();
        ps = conn.prepareStatement(sql);

        ps.setInt(1,userid);
        ps.setInt(2,articleid);
        ps.setString(3,commentContent);
        ps.setString(4,username);
        ps.setString(5,createTime);

        int result = ps.executeUpdate();
        DBUtil.close(null,ps,conn);

        return result;
    }

    @Override
    public List<Comment> findCommentById(int newsId) throws SQLException {
        List<Comment> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet set = null;
        String sql = "select * from comment where articleid = ?";
        conn = DBUtil.getConnection();
        ps = conn.prepareStatement(sql);
        ps.setInt(1,newsId);
        set = ps.executeQuery();
        while (set.next()){
            int commentid = set.getInt(1);
            int articleid = set.getInt(2);
            String comment_content = set.getString(3);
            String username = set.getString(4);
            String comment_date = set.getString(5);
            int userid = set.getInt(6);
            Comment comment = new Comment(commentid,articleid,userid,comment_content,username,comment_date);
            list.add(comment);
        }
        return list;
    }
}
